{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 46,
   "metadata": {},
   "outputs": [],
   "source": [
    "import pandas as pd\n",
    "import numpy as np\n",
    "import os\n",
    "import sys\n",
    "sys.path.append(r'D:\\codeproject\\data-process')\n",
    "import pyhrv.nonlinear as nl  # 导入pyHRV的非线性分析模块\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 47,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "ID                             object\n",
      "Gender                         object\n",
      "Age                           float64\n",
      "Lactate Threshold (mmol/L)    float64\n",
      "HR Threshold (bpm)            float64\n",
      "Threshold Speed (km/h)        float64\n",
      "HR_max                        float64\n",
      "number                          int32\n",
      "dtype: object\n",
      "rrdatapath          object\n",
      "data_path           object\n",
      "id                   int64\n",
      "polar采集开始           object\n",
      "polar采集结束           object\n",
      "healthtest_path     object\n",
      "singlework_path     object\n",
      "day                  int64\n",
      "state               object\n",
      "healthtest-HR      float64\n",
      "healthtest-HRV     float64\n",
      "healthtest-type     object\n",
      "跑步开始时间              object\n",
      "跑步结束时间              object\n",
      "全程rr                object\n",
      "全程hr                object\n",
      "psychology_RPE      object\n",
      "physiology_RPE      object\n",
      "now_RPE             object\n",
      "train_RPE           object\n",
      "dtype: object\n"
     ]
    }
   ],
   "source": [
    "all_stages_path=r'D:\\学习&科研\\华为手表项目\\华为数据\\base-data\\longfile_df.csv'\n",
    "all_stages_df=pd.read_csv(all_stages_path)\n",
    "laandmaxhr=pd.read_csv(r'D:\\学习&科研\\华为手表项目\\华为数据\\base-data\\Processed_summary_Mod(2).csv')\n",
    "laandmaxhr[\"number\"]=laandmaxhr['ID'].astype(str).str[:4].astype(int)\n",
    "print(laandmaxhr.dtypes)\n",
    "print(all_stages_df.dtypes)\n",
    "test_record_df = pd.merge(all_stages_df, laandmaxhr, left_on='id', right_on='number', how='left')\n",
    "del test_record_df['ID']\n",
    "del test_record_df['number']\n",
    "del test_record_df['HR_max']\n",
    "test_record_df['Gender'] = test_record_df['Gender'].replace({'男': 1, '女': 0})\n",
    "test_record_df.to_csv(r'D:\\学习&科研\\华为手表项目\\华为数据\\base-data\\规律跑者+验血.csv',index=False)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 49,
   "metadata": {},
   "outputs": [],
   "source": [
    "#polar_rr为列表数据，通过函数计算得到指标，加入该行\n",
    "#polar_rr为列表数据，通过函数计算得到指标，加入该行\n",
    "# 定义 calculate_sd1_sd2 函数\n",
    "all_stages_df=pd.read_csv(r'D:\\学习&科研\\华为手表项目\\华为数据\\base-data\\规律跑者+验血.csv')\n",
    "all_stages_df['全程rr'] = all_stages_df['全程rr'].apply(lambda x: eval(x) if isinstance(x, str) else x)\n",
    "\n",
    "all_stages_df['全程hr'] = all_stages_df['全程hr'].apply(lambda x: eval(x) if isinstance(x, str) else x) \n",
    "\n",
    "# 定义 calculate_sd1_sd2 函数\n",
    "def calculate_sd1_sd2(rr_intervals):\n",
    "    if not isinstance(rr_intervals, (list, np.ndarray)) or len(rr_intervals) < 2:\n",
    "        return np.nan, np.nan  # 如果数据不符合要求，返回 NaN\n",
    "    \n",
    "    rr_diff = np.diff(rr_intervals)\n",
    "    rr_diff_n = rr_diff[:-1]\n",
    "    rr_diff_np1 = rr_diff[1:]\n",
    "\n",
    "    SD1 = np.sqrt(np.std(rr_diff_n - rr_diff_np1, ddof=1) / 2)\n",
    "    SD2 = np.sqrt(np.std(rr_diff_n + rr_diff_np1, ddof=1) / 2)\n",
    "\n",
    "    return SD1, SD2\n",
    "def calculate_sdnn_rmssd(rr_intervals):\n",
    "    \n",
    "    SDNN = np.std(rr_intervals, ddof=1)  # SDNN的计算\n",
    "    RMSSD = np.sqrt(np.mean(np.square(np.diff(rr_intervals))))  # RMSSD的计算\n",
    "    return SDNN, RMSSD\n",
    "def calculate_cv(rr_intervals):\n",
    "    mean_rr = np.mean(rr_intervals)\n",
    "    std_rr = np.std(rr_intervals, ddof=1)\n",
    "    cv = std_rr / mean_rr if mean_rr != 0 else 0\n",
    "    mean_hr = 60000 / mean_rr\n",
    "    return cv, mean_hr\n",
    "\n",
    "def calculate_dfa(rr_intervals):\n",
    "    # 使用pyHRV计算DFA\n",
    "    dfa_result = nl.dfa(rr_intervals ,show=False)\n",
    "    alpha1 = dfa_result['dfa_alpha1']  # DFA的短期指数\n",
    "    alpha2 = dfa_result['dfa_alpha2']  # DFA的长期指数\n",
    "    return alpha1, alpha2\n",
    "# 应用 calculate_sd1_sd2 函数并提取 SD1 和 SD2\n",
    "# all_stages_df[['SD1', 'SD2']] = all_stages_df['polar_rr'].apply(lambda x: pd.Series(calculate_sd1_sd2(x)))\n",
    "\n",
    "# all_stages_df[['SDNN', 'RMSSD']] = all_stages_df['polar_rr'].apply(lambda x: pd.Series(calculate_sdnn_rmssd(x)))\n",
    "# all_stages_df[['CV', 'Mean_HR']] = all_stages_df['polar_rr'].apply(lambda x: pd.Series(calculate_cv(x)))\n",
    "# all_stages_df[['alpha1', 'alpha2']] = all_stages_df['polar_rr'].apply(lambda x: pd.Series(calculate_dfa(x)))\n",
    "#指定某几列数据为数字类型\n",
    "\n",
    "all_stages_df[['SDNN', 'RMSSD']] = all_stages_df['全程rr'].apply(lambda x: pd.Series(calculate_sdnn_rmssd(x)))\n",
    "# all_stages_df[['CV', 'Mean_HR']] = all_stages_df['polar_rr'].apply(lambda x: pd.Series(calculate_cv(x)))\n",
    "# all_stages_df[['alpha1', 'alpha2']] = all_stages_df['polar_rr'].apply(lambda x: pd.Series(calculate_dfa(x)))\n",
    "#指定某几列数据为数字类型\n",
    "# all_stages_df[['SD1', 'SD2','SDNN', 'RMSSD','CV', 'Mean_HR']] = all_stages_df[['SD1', 'SD2','SDNN', 'RMSSD','CV', 'Mean_HR']].astype(float)  # 或 int\n",
    "\n",
    "\n",
    "del all_stages_df['rrdatapath']\n",
    "del all_stages_df['data_path']\n",
    "del all_stages_df['healthtest_path']\n",
    "del all_stages_df['singlework_path']\n",
    "all_stages_df.to_csv(r'D:\\学习&科研\\华为手表项目\\华为数据\\base-data\\规律跑者+验血+hrv.csv',index=False)\n",
    "\n"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "MLandDL",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.8.20"
  },
  "orig_nbformat": 4
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
